package com.sphd.emanu.activity.addcard;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.pojo.bank.BankMessageInfo;
import com.sphd.emanu.pojo.login.User;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class AddCardActivity extends MVPBaseActivity<AddCardContract.View, AddCardPresenter> implements AddCardContract.View {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.card_name)
    MaterialEditText cardName;
    @BindView(R.id.card_from)
    MaterialEditText cardFrom;
    @BindView(R.id.card_num)
    MaterialEditText cardNum;
    @BindView(R.id.card_first_money)
    MaterialEditText cardFirstMoney;
    @BindView(R.id.jbh_radio)
    RadioButton jbhRadio;
    @BindView(R.id.fjbh_radio)
    RadioButton fjbhRadio;
    @BindView(R.id.cashable_no_radiobutton)
    RadioButton cashableNoRadiobutton;
    @BindView(R.id.cashable_yes_radiobutton)
    RadioButton cashableYesRadiobutton;
    @BindView(R.id.cashable_radio_group)
    RadioGroup cashableRadioGroup;
    @BindView(R.id.card_note)
    MaterialEditText cardNote;
    @BindView(R.id.ok_button)
    Button okButton;
    Intent intent;
    Bundle bundle;
    BankMessageInfo bankMessageInfo;
    boolean isAdd = false;
    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_card);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        isAdd = bundle.getBoolean(Constant.IS_ADD);
        if (isAdd) {
            setTitleBar(toolbar, "添加银行");
        } else {
            setTitleBar(toolbar, "修改银行");
            bankMessageInfo = (BankMessageInfo) bundle.getSerializable(Constant.BANKMESSAGEINFO);
            setBankMessageInfo();
        }
    }

    private void setBankMessageInfo() {
        cardFrom.setText(bankMessageInfo.getBankName());
        cardNum.setText(bankMessageInfo.getAccount());
        cardFirstMoney.setText(bankMessageInfo.getInitialAmount() + "");
        cardName.setText(bankMessageInfo.getName());
        cardNote.setText(bankMessageInfo.getMemo());
        if (bankMessageInfo.getOperation().equals("基本户")) {
            jbhRadio.setChecked(true);
            fjbhRadio.setChecked(false);
        } else {
            fjbhRadio.setChecked(true);
            jbhRadio.setChecked(false);
        }
        if (bankMessageInfo.getCashable() == 1) {
            cashableYesRadiobutton.setChecked(true);
            cashableNoRadiobutton.setChecked(false);
        } else {
            cashableNoRadiobutton.setChecked(true);
            cashableYesRadiobutton.setChecked(false);
        }
    }

    @OnClick(R.id.ok_button)
    public void onViewClicked() {
        if (TextUtils.isEmpty(cardFirstMoney.getText()) ||
                !isNum(cardFirstMoney.getText().toString())) {
            cardFirstMoney.setError("输入金额错误");

        } else {
            showProgressDialog();
            if (isAdd) {//添加帐户
                mPresenter.addAccount(getSaveAccount(
                        jbhRadio.isChecked() ? "基本户" : "非基本户", cashableYesRadiobutton.isChecked() ? 1 : 2));

            } else {//修改帐户
                bankMessageInfo.setBankName(cardFrom.getText().toString());
                bankMessageInfo.setAccount(cardNum.getText().toString());
                bankMessageInfo.setInitialAmount(Double.valueOf(cardFirstMoney.getText().toString()));
                bankMessageInfo.setName(cardName.getText().toString());
                bankMessageInfo.setMemo(cardNote.getText().toString());
                bankMessageInfo.setOperation(jbhRadio.isChecked() ? "基本户" : "非基本户");
                bankMessageInfo.setCashable(cashableYesRadiobutton.isChecked() ? 1 : 2);
                mPresenter.changeAccountRequest(getChangeAccount());
            }
        }
    }

    public Map<String, String> getChangeAccount() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("bankAccountId", "" + bankMessageInfo.getId());
        map.put("bankName", bankMessageInfo.getBankName());
        map.put("account", bankMessageInfo.getAccount());
        map.put("initialAmount", bankMessageInfo.getInitialAmount() + "");
        map.put("name", bankMessageInfo.getName());
        map.put("memo", bankMessageInfo.getMemo());
        map.put("operation", bankMessageInfo.getOperation());
        map.put("userId", String.valueOf(user.getUserid()));
        map.put("accountStatus", bankMessageInfo.getAccountStatus() + "");
        map.put("accountType", bankMessageInfo.getAccountType() + "");
        map.put("illustrate", "");

        return map;
    }

    public Map<String, String> getSaveAccount(String operation, int cashable) {
        Map<String, String> map = new HashMap<String, String>();
                /*传入参数 bankName 开户行  account帐号 balance初始资金  name户名  oid 学校id，uid创建人id（当前登陆人*/
        map.put("bankName", bankMessageInfo.getBankName());
        map.put("account", bankMessageInfo.getAccount());
        map.put("initialAmount", bankMessageInfo.getInitialAmount() + "");
        map.put("name", bankMessageInfo.getName());
        map.put("memo", bankMessageInfo.getMemo());
        map.put("oid", String.valueOf(user.getOid()));
        map.put("operation", operation);
        map.put("uid", String.valueOf(user.getUserid()));
        map.put("cashable", "" + cashable);
        return map;
    }

    /*测试是不是非负数*/
    private boolean isNum(String str) {

        String pattern = "^[-+]?\\d+(\\.\\d+)?$";//验证是不是数字开头

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        System.out.println(m.matches());
        return m.matches();
    }

    @Override
    public void success(String result) {
        dissProgressDialog();
        String toastString;
        switch (result) {
            case "success":
                toastString = "成功";
            case "existence":
                toastString = "已存在或者是已存在基本户";
            case "notSufficientFunds":
                toastString = "输入金额可能导致余额为负数";
            default:
                toastString = "错误";
        }
        toast(toastString);
    }
}
